package com.ubao.ui.ratingbar;



import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ubao.R;




public class Ratingbar extends LinearLayout {
    private int[] ids = {R.id.iv1,R.id.iv2,R.id.iv3,R.id.iv4,R.id.iv5};
	private ImageView[] ivStars = new ImageView[ids.length];
	private int[] imgs = {R.drawable.zc_star,R.drawable.zc_start_select};
	private int rating;
	public Ratingbar(Context context) {
		super(context);
		init(context);
	}

	public Ratingbar(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		Resources resource = getResources();
//		this.setMeasuredDimension(RelativeLayout.LayoutParams.FILL_PARENT,
//				(int) resource.getDimension(R.dimen.titlebar_height));
		this.setGravity(Gravity.CENTER_VERTICAL);
		this.setWeightSum(1);
 
		// Inflate the view from the layout resource.
		String infService = Context.LAYOUT_INFLATER_SERVICE;
		LayoutInflater li = (LayoutInflater) context
				.getSystemService(infService);
		li.inflate(R.layout.widge_ratingbar, this);
		InitViews();
	}

	private void InitViews() {
		for(int i=0;i<ids.length;i++){
			ivStars[i] = (ImageView) findViewById(ids[i]);
			ivStars[i].setOnClickListener(listener);
		}
	}
	
	public void clickable(boolean clickable){
		for(int i=0;i<ivStars.length;i++){
			ivStars[i].setClickable(clickable);
		}
	}
	
	public void setImgs(int unselected,int selected){
		imgs[0] = unselected;
		imgs[1] = selected;
	}
	
	public void setRating(int rate){
		for(int i=0;i<ivStars.length;i++){
			ivStars[i].setImageResource(imgs[0]);
		}
		switch(rate){
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
			rating = rate;
			for(int i=0;i<=ivStars.length;i++){
				if(i<rate){
					ivStars[i].setImageResource(imgs[1]);
				}
			}
			break;
		}
	}
	
	private OnClickListener listener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			boolean isEqual = false;
			for(int i=0;i<ivStars.length;i++){
				if(ids[i]!=v.getId()){
					if(isEqual){
						ivStars[i].setImageResource(imgs[0]);
					}else{
						ivStars[i].setImageResource(imgs[1]);
					}
				}else{
					ivStars[i].setImageResource(imgs[1]);
					isEqual = true;
				}
			}
		}
	};
	
	public int getRating(){
		return rating;
	}
	
}
